[[...path]].page.tsx 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708
  1. import type { ReactNode } from 'react';
  2. import React, { useEffect } from 'react';
  3. import EventEmitter from 'events';
  4. import { isIPageInfo } from '@growi/core';
  5. import type {
  6. IDataWithMeta, IPageInfo, IPagePopulatedToShowRevision,
  7. } from '@growi/core';
  8. import {
  9. isClient, pagePathUtils, pathUtils,
  10. } from '@growi/core/dist/utils';
  11. import ExtensibleCustomError from 'extensible-custom-error';
  12. import type {
  13. GetServerSideProps, GetServerSidePropsContext,
  14. } from 'next';
  15. import { serverSideTranslations } from 'next-i18next/serverSideTranslations';
  16. import dynamic from 'next/dynamic';
  17. import Head from 'next/head';
  18. import { useRouter } from 'next/router';
  19. import superjson from 'superjson';
  20. import { BasicLayout } from '~/components/Layout/BasicLayout';
  21. import { PageView } from '~/components/PageView/PageView';
  22. import { DrawioViewerScript } from '~/components/Script/DrawioViewerScript';
  23. import { SupportedAction, type SupportedActionType } from '~/interfaces/activity';
  24. import type { CrowiRequest } from '~/interfaces/crowi-request';
  25. import { RegistrationMode } from '~/interfaces/registration-mode';
  26. import type { RendererConfig } from '~/interfaces/services/renderer';
  27. import type { ISidebarConfig } from '~/interfaces/sidebar-config';
  28. import type { CurrentPageYjsData } from '~/interfaces/yjs';
  29. import type { PageModel, PageDocument } from '~/server/models/page';
  30. import type { PageRedirectModel } from '~/server/models/page-redirect';
  31. import { useEditorModeClassName } from '~/services/layout/use-editor-mode-class-name';
  32. import {
  33. useCurrentUser,
  34. useIsForbidden, useIsSharedUser,
  35. useIsEnabledStaleNotification, useIsIdenticalPath,
  36. useIsSearchServiceConfigured, useIsSearchServiceReachable, useDisableLinkSharing,
  37. useDefaultIndentSize, useIsIndentSizeForced,
  38. useIsAclEnabled, useIsSearchPage, useIsEnabledAttachTitleHeader,
  39. useCsrfToken, useIsSearchScopeChildrenAsDefault, useIsEnabledMarp, useCurrentPathname,
  40. useIsSlackConfigured, useRendererConfig, useGrowiCloudUri,
  41. useIsAllReplyShown, useShowPageSideAuthors, useIsContainerFluid, useIsNotCreatable,
  42. useIsUploadAllFileAllowed, useIsUploadEnabled,
  43. useElasticsearchMaxBodyLengthToIndex,
  44. useIsLocalAccountRegistrationEnabled,
  45. useIsRomUserAllowedToComment,
  46. useIsAiEnabled, useLimitLearnablePageCountPerAssistant,
  47. } from '~/stores-universal/context';
  48. import { useEditingMarkdown } from '~/stores/editor';
  49. import {
  50. useSWRxCurrentPage, useSWRMUTxCurrentPage, useCurrentPageId,
  51. useIsNotFound, useIsLatestRevision, useTemplateTagData, useTemplateBodyData,
  52. } from '~/stores/page';
  53. import { useRedirectFrom } from '~/stores/page-redirect';
  54. import { useRemoteRevisionId } from '~/stores/remote-latest-page';
  55. import { useSetupGlobalSocket, useSetupGlobalSocketForPage } from '~/stores/websocket';
  56. import { useCurrentPageYjsData, useSWRMUTxCurrentPageYjsData } from '~/stores/yjs';
  57. import loggerFactory from '~/utils/logger';
  58. import type { NextPageWithLayout } from './_app.page';
  59. import type { CommonProps } from './utils/commons';
  60. import {
  61. getNextI18NextConfig, getServerSideCommonProps, generateCustomTitleForPage, useInitSidebarConfig, skipSSR, addActivity,
  62. } from './utils/commons';
  63. declare global {
  64. // eslint-disable-next-line vars-on-top, no-var
  65. var globalEmitter: EventEmitter;
  66. }
  67. const GrowiContextualSubNavigationSubstance = dynamic(() => import('~/client/components/Navbar/GrowiContextualSubNavigation'), { ssr: false });
  68. const GrowiPluginsActivator = dynamic(() => import('~/features/growi-plugin/client/components').then(mod => mod.GrowiPluginsActivator), { ssr: false });
  69. const DisplaySwitcher = dynamic(() => import('~/client/components/Page/DisplaySwitcher').then(mod => mod.DisplaySwitcher), { ssr: false });
  70. const PageStatusAlert = dynamic(() => import('~/client/components/PageStatusAlert').then(mod => mod.PageStatusAlert), { ssr: false });
  71. const UnsavedAlertDialog = dynamic(() => import('~/client/components/UnsavedAlertDialog'), { ssr: false });
  72. const DescendantsPageListModal = dynamic(
  73. () => import('~/client/components/DescendantsPageListModal').then(mod => mod.DescendantsPageListModal),
  74. { ssr: false },
  75. );
  76. const DrawioModal = dynamic(() => import('~/client/components/PageEditor/DrawioModal').then(mod => mod.DrawioModal), { ssr: false });
  77. const HandsontableModal = dynamic(() => import('~/client/components/PageEditor/HandsontableModal').then(mod => mod.HandsontableModal), { ssr: false });
  78. const TemplateModal = dynamic(() => import('~/client/components/TemplateModal').then(mod => mod.TemplateModal), { ssr: false });
  79. const LinkEditModal = dynamic(() => import('~/client/components/PageEditor/LinkEditModal').then(mod => mod.LinkEditModal), { ssr: false });
  80. const TagEditModal = dynamic(() => import('~/client/components/PageTags/TagEditModal').then(mod => mod.TagEditModal), { ssr: false });
  81. const ConflictDiffModal = dynamic(() => import('~/client/components/PageEditor/ConflictDiffModal').then(mod => mod.ConflictDiffModal), { ssr: false });
  82. const QuestionnaireModalManager = dynamic(() => import('~/features/questionnaire/client/components/QuestionnaireModalManager'), { ssr: false });
  83. const EditablePageEffects = dynamic(() => import('~/client/components/Page/EditablePageEffects').then(mod => mod.EditablePageEffects), { ssr: false });
  84. const logger = loggerFactory('growi:pages:all');
  85. const {
  86. isPermalink: _isPermalink, isCreatablePage,
  87. } = pagePathUtils;
  88. const { removeHeadingSlash } = pathUtils;
  89. type IPageToShowRevisionWithMeta = IDataWithMeta<IPagePopulatedToShowRevision & PageDocument, IPageInfo>;
  90. type IPageToShowRevisionWithMetaSerialized = IDataWithMeta<string, string>;
  91. superjson.registerCustom<IPageToShowRevisionWithMeta, IPageToShowRevisionWithMetaSerialized>(
  92. {
  93. isApplicable: (v): v is IPageToShowRevisionWithMeta => {
  94. return v?.data != null
  95. && v?.data.toObject != null
  96. && isIPageInfo(v.meta);
  97. },
  98. serialize: (v) => {
  99. return {
  100. data: superjson.stringify(v.data.toObject()),
  101. meta: superjson.stringify(v.meta),
  102. };
  103. },
  104. deserialize: (v) => {
  105. return {
  106. data: superjson.parse(v.data),
  107. meta: v.meta != null ? superjson.parse(v.meta) : undefined,
  108. };
  109. },
  110. },
  111. 'IPageToShowRevisionWithMetaTransformer',
  112. );
  113. // GrowiContextualSubNavigation for NOT shared page
  114. type GrowiContextualSubNavigationProps = {
  115. isLinkSharingDisabled: boolean,
  116. }
  117. const GrowiContextualSubNavigation = (props: GrowiContextualSubNavigationProps): JSX.Element => {
  118. const { isLinkSharingDisabled } = props;
  119. const { data: currentPage } = useSWRxCurrentPage();
  120. return (
  121. <GrowiContextualSubNavigationSubstance currentPage={currentPage} isLinkSharingDisabled={isLinkSharingDisabled} />
  122. );
  123. };
  124. type Props = CommonProps & {
  125. pageWithMeta: IPageToShowRevisionWithMeta | null,
  126. // pageUser?: any,
  127. redirectFrom?: string;
  128. // shareLinkId?: string;
  129. isLatestRevision?: boolean,
  130. isIdenticalPathPage?: boolean,
  131. isForbidden: boolean,
  132. isNotFound: boolean,
  133. isNotCreatable: boolean,
  134. // isAbleToDeleteCompletely: boolean,
  135. templateTagData?: string[],
  136. templateBodyData?: string,
  137. isLocalAccountRegistrationEnabled: boolean,
  138. isSearchServiceConfigured: boolean,
  139. isSearchServiceReachable: boolean,
  140. isSearchScopeChildrenAsDefault: boolean,
  141. elasticsearchMaxBodyLengthToIndex: number,
  142. isEnabledMarp: boolean,
  143. isRomUserAllowedToComment: boolean,
  144. sidebarConfig: ISidebarConfig,
  145. isSlackConfigured: boolean,
  146. // isMailerSetup: boolean,
  147. isAclEnabled: boolean,
  148. // hasSlackConfig: boolean,
  149. drawioUri: string | null,
  150. // highlightJsStyle: string,
  151. isAllReplyShown: boolean,
  152. showPageSideAuthors: boolean,
  153. isContainerFluid: boolean,
  154. isUploadEnabled: boolean,
  155. isUploadAllFileAllowed: boolean,
  156. isEnabledStaleNotification: boolean,
  157. isEnabledAttachTitleHeader: boolean,
  158. // isEnabledLinebreaks: boolean,
  159. // isEnabledLinebreaksInComments: boolean,
  160. adminPreferredIndentSize: number,
  161. isIndentSizeForced: boolean,
  162. disableLinkSharing: boolean,
  163. skipSSR: boolean,
  164. ssrMaxRevisionBodyLength: number,
  165. yjsData: CurrentPageYjsData,
  166. rendererConfig: RendererConfig,
  167. aiEnabled: boolean,
  168. limitLearnablePageCountPerAssistant: number,
  169. };
  170. const Page: NextPageWithLayout<Props> = (props: Props) => {
  171. // register global EventEmitter
  172. if (isClient() && window.globalEmitter == null) {
  173. window.globalEmitter = new EventEmitter();
  174. }
  175. const router = useRouter();
  176. useCurrentUser(props.currentUser ?? null);
  177. // commons
  178. useCsrfToken(props.csrfToken);
  179. useGrowiCloudUri(props.growiCloudUri);
  180. // page
  181. useIsContainerFluid(props.isContainerFluid);
  182. // useOwnerOfCurrentPage(props.pageUser != null ? JSON.parse(props.pageUser) : null);
  183. useIsForbidden(props.isForbidden);
  184. useIsNotCreatable(props.isNotCreatable);
  185. useRedirectFrom(props.redirectFrom ?? null);
  186. useIsSharedUser(false); // this page cann't be routed for '/share'
  187. useIsIdenticalPath(props.isIdenticalPathPage ?? false);
  188. useIsEnabledStaleNotification(props.isEnabledStaleNotification);
  189. useIsSearchPage(false);
  190. useIsEnabledAttachTitleHeader(props.isEnabledAttachTitleHeader);
  191. useIsSearchServiceConfigured(props.isSearchServiceConfigured);
  192. useIsSearchServiceReachable(props.isSearchServiceReachable);
  193. useElasticsearchMaxBodyLengthToIndex(props.elasticsearchMaxBodyLengthToIndex);
  194. useIsSearchScopeChildrenAsDefault(props.isSearchScopeChildrenAsDefault);
  195. useIsSlackConfigured(props.isSlackConfigured);
  196. // useIsMailerSetup(props.isMailerSetup);
  197. useIsAclEnabled(props.isAclEnabled);
  198. // useHasSlackConfig(props.hasSlackConfig);
  199. useDefaultIndentSize(props.adminPreferredIndentSize);
  200. useIsIndentSizeForced(props.isIndentSizeForced);
  201. useDisableLinkSharing(props.disableLinkSharing);
  202. useRendererConfig(props.rendererConfig);
  203. useIsEnabledMarp(props.rendererConfig.isEnabledMarp);
  204. // useRendererSettings(props.rendererSettingsStr != null ? JSON.parse(props.rendererSettingsStr) : undefined);
  205. // useGrowiRendererConfig(props.growiRendererConfigStr != null ? JSON.parse(props.growiRendererConfigStr) : undefined);
  206. useIsAllReplyShown(props.isAllReplyShown);
  207. useShowPageSideAuthors(props.showPageSideAuthors);
  208. useIsUploadAllFileAllowed(props.isUploadAllFileAllowed);
  209. useIsUploadEnabled(props.isUploadEnabled);
  210. useIsLocalAccountRegistrationEnabled(props.isLocalAccountRegistrationEnabled);
  211. useIsRomUserAllowedToComment(props.isRomUserAllowedToComment);
  212. useIsAiEnabled(props.aiEnabled);
  213. useLimitLearnablePageCountPerAssistant(props.limitLearnablePageCountPerAssistant);
  214. const { pageWithMeta } = props;
  215. const pageId = pageWithMeta?.data._id;
  216. const revisionId = pageWithMeta?.data.revision?._id;
  217. const revisionBody = pageWithMeta?.data.revision?.body;
  218. useCurrentPathname(props.currentPathname);
  219. const { data: currentPage } = useSWRxCurrentPage(pageWithMeta?.data ?? null); // store initial data
  220. const { trigger: mutateCurrentPage } = useSWRMUTxCurrentPage();
  221. const { trigger: mutateCurrentPageYjsDataFromApi } = useSWRMUTxCurrentPageYjsData();
  222. const { mutate: mutateEditingMarkdown } = useEditingMarkdown();
  223. const { data: currentPageId, mutate: mutateCurrentPageId } = useCurrentPageId();
  224. const { mutate: mutateIsNotFound } = useIsNotFound();
  225. const { mutate: mutateIsLatestRevision } = useIsLatestRevision();
  226. const { mutate: mutateRemoteRevisionId } = useRemoteRevisionId();
  227. const { mutate: mutateTemplateTagData } = useTemplateTagData();
  228. const { mutate: mutateTemplateBodyData } = useTemplateBodyData();
  229. const { mutate: mutateCurrentPageYjsData } = useCurrentPageYjsData();
  230. useSetupGlobalSocket();
  231. useSetupGlobalSocketForPage(pageId);
  232. // Store initial data (When revisionBody is not SSR)
  233. useEffect(() => {
  234. if (!props.skipSSR) {
  235. return;
  236. }
  237. if (currentPageId != null && revisionId != null && !props.isNotFound) {
  238. const mutatePageData = async() => {
  239. const pageData = await mutateCurrentPage();
  240. mutateEditingMarkdown(pageData?.revision?.body);
  241. };
  242. // If skipSSR is true, use the API to retrieve page data.
  243. // Because pageWIthMeta does not contain revision.body
  244. mutatePageData();
  245. }
  246. }, [
  247. revisionId, currentPageId, mutateCurrentPage,
  248. mutateCurrentPageYjsDataFromApi, mutateEditingMarkdown, props.isNotFound, props.skipSSR,
  249. ]);
  250. // Load current yjs data
  251. useEffect(() => {
  252. if (currentPageId != null && revisionId != null && !props.isNotFound) {
  253. mutateCurrentPageYjsDataFromApi();
  254. }
  255. }, [currentPageId, mutateCurrentPageYjsDataFromApi, props.isNotFound, revisionId]);
  256. // sync pathname by Shallow Routing https://nextjs.org/docs/routing/shallow-routing
  257. useEffect(() => {
  258. const decodedURI = decodeURI(window.location.pathname);
  259. if (isClient() && decodedURI !== props.currentPathname) {
  260. const { search, hash } = window.location;
  261. router.replace(`${props.currentPathname}${search}${hash}`, undefined, { shallow: true });
  262. }
  263. }, [props.currentPathname, router]);
  264. // initialize mutateEditingMarkdown only once per page
  265. // need to include useCurrentPathname not useCurrentPagePath
  266. useEffect(() => {
  267. if (props.currentPathname != null) {
  268. mutateEditingMarkdown(revisionBody);
  269. }
  270. }, [mutateEditingMarkdown, revisionBody, props.currentPathname]);
  271. useEffect(() => {
  272. mutateRemoteRevisionId(revisionId);
  273. }, [mutateRemoteRevisionId, revisionId]);
  274. useEffect(() => {
  275. mutateCurrentPageId(pageId ?? null);
  276. }, [mutateCurrentPageId, pageId]);
  277. useEffect(() => {
  278. mutateIsNotFound(props.isNotFound);
  279. }, [mutateIsNotFound, props.isNotFound]);
  280. useEffect(() => {
  281. mutateIsLatestRevision(props.isLatestRevision);
  282. }, [mutateIsLatestRevision, props.isLatestRevision]);
  283. useEffect(() => {
  284. mutateTemplateTagData(props.templateTagData);
  285. }, [props.templateTagData, mutateTemplateTagData]);
  286. useEffect(() => {
  287. mutateTemplateBodyData(props.templateBodyData);
  288. }, [props.templateBodyData, mutateTemplateBodyData]);
  289. useEffect(() => {
  290. mutateCurrentPageYjsData(props.yjsData);
  291. }, [mutateCurrentPageYjsData, props.yjsData]);
  292. // If the data on the page changes without router.push, pageWithMeta remains old because getServerSideProps() is not executed
  293. // So preferentially take page data from useSWRxCurrentPage
  294. const pagePath = currentPage?.path ?? pageWithMeta?.data.path ?? props.currentPathname;
  295. const title = generateCustomTitleForPage(props, pagePath);
  296. return (
  297. <>
  298. <Head>
  299. <title>{title}</title>
  300. </Head>
  301. <div className="dynamic-layout-root justify-content-between">
  302. <GrowiContextualSubNavigation isLinkSharingDisabled={props.disableLinkSharing} />
  303. <PageView
  304. className="d-edit-none"
  305. pagePath={pagePath}
  306. initialPage={pageWithMeta?.data}
  307. rendererConfig={props.rendererConfig}
  308. />
  309. <EditablePageEffects />
  310. <DisplaySwitcher />
  311. <PageStatusAlert />
  312. </div>
  313. </>
  314. );
  315. };
  316. const BasicLayoutWithEditor = ({ children }: { children?: ReactNode }): JSX.Element => {
  317. const editorModeClassName = useEditorModeClassName();
  318. return <BasicLayout className={editorModeClassName}>{children}</BasicLayout>;
  319. };
  320. type LayoutProps = Props & {
  321. children?: ReactNode
  322. }
  323. const Layout = ({ children, ...props }: LayoutProps): JSX.Element => {
  324. // init sidebar config with UserUISettings and sidebarConfig
  325. useInitSidebarConfig(props.sidebarConfig, props.userUISettings);
  326. return <BasicLayoutWithEditor>{children}</BasicLayoutWithEditor>;
  327. };
  328. Page.getLayout = function getLayout(page: React.ReactElement<Props>) {
  329. return (
  330. <>
  331. <GrowiPluginsActivator />
  332. <DrawioViewerScript drawioUri={page.props.rendererConfig.drawioUri} />
  333. <Layout {...page.props}>
  334. {page}
  335. </Layout>
  336. <UnsavedAlertDialog />
  337. <DescendantsPageListModal />
  338. <DrawioModal />
  339. <HandsontableModal />
  340. <QuestionnaireModalManager />
  341. <TemplateModal />
  342. <LinkEditModal />
  343. <TagEditModal />
  344. <ConflictDiffModal />
  345. </>
  346. );
  347. };
  348. function getPageIdFromPathname(currentPathname: string): string | null {
  349. return _isPermalink(currentPathname) ? removeHeadingSlash(currentPathname) : null;
  350. }
  351. class MultiplePagesHitsError extends ExtensibleCustomError {
  352. pagePath: string;
  353. constructor(pagePath: string) {
  354. super(`MultiplePagesHitsError occured by '${pagePath}'`);
  355. this.pagePath = pagePath;
  356. }
  357. }
  358. async function injectPageData(context: GetServerSidePropsContext, props: Props): Promise<void> {
  359. const { model: mongooseModel } = await import('mongoose');
  360. const req: CrowiRequest = context.req as CrowiRequest;
  361. const { crowi } = req;
  362. const { revisionId } = req.query;
  363. const Page = crowi.model('Page') as PageModel;
  364. const PageRedirect = mongooseModel('PageRedirect') as PageRedirectModel;
  365. const { pageService, configManager } = crowi;
  366. let currentPathname = props.currentPathname;
  367. const pageId = getPageIdFromPathname(currentPathname);
  368. const isPermalink = _isPermalink(currentPathname);
  369. const { user } = req;
  370. if (!isPermalink) {
  371. // check redirects
  372. const chains = await PageRedirect.retrievePageRedirectEndpoints(currentPathname);
  373. if (chains != null) {
  374. // overwrite currentPathname
  375. currentPathname = chains.end.toPath;
  376. props.currentPathname = currentPathname;
  377. // set redirectFrom
  378. props.redirectFrom = chains.start.fromPath;
  379. }
  380. // check whether the specified page path hits to multiple pages
  381. const count = await Page.countByPathAndViewer(currentPathname, user, null, true);
  382. if (count > 1) {
  383. throw new MultiplePagesHitsError(currentPathname);
  384. }
  385. }
  386. const pageWithMeta = await pageService.findPageAndMetaDataByViewer(pageId, currentPathname, user, true); // includeEmpty = true, isSharedPage = false
  387. const { data: page, meta } = pageWithMeta ?? {};
  388. // add user to seen users
  389. if (page != null && user != null) {
  390. await page.seen(user);
  391. }
  392. props.pageWithMeta = null;
  393. // populate & check if the revision is latest
  394. if (page != null) {
  395. page.initLatestRevisionField(revisionId);
  396. props.isLatestRevision = page.isLatestRevision();
  397. const ssrMaxRevisionBodyLength = configManager.getConfig('app:ssrMaxRevisionBodyLength');
  398. props.skipSSR = await skipSSR(page, ssrMaxRevisionBodyLength);
  399. const populatedPage = await page.populateDataToShowRevision(props.skipSSR); // shouldExcludeBody = skipSSR
  400. props.pageWithMeta = {
  401. data: populatedPage,
  402. meta,
  403. };
  404. }
  405. }
  406. async function injectRoutingInformation(context: GetServerSidePropsContext, props: Props): Promise<void> {
  407. const req: CrowiRequest = context.req as CrowiRequest;
  408. const { crowi } = req;
  409. const Page = crowi.model('Page') as PageModel;
  410. const { currentPathname } = props;
  411. const pageId = getPageIdFromPathname(currentPathname);
  412. const isPermalink = _isPermalink(currentPathname);
  413. const page = props.pageWithMeta?.data;
  414. if (props.isIdenticalPathPage) {
  415. props.isNotCreatable = true;
  416. }
  417. else if (page == null) {
  418. props.isNotFound = true;
  419. props.isNotCreatable = !isCreatablePage(currentPathname);
  420. // check the page is forbidden or just does not exist.
  421. const count = isPermalink ? await Page.count({ _id: pageId }) : await Page.count({ path: currentPathname });
  422. props.isForbidden = count > 0;
  423. }
  424. else {
  425. props.isNotFound = page.isEmpty;
  426. props.isNotCreatable = false;
  427. props.isForbidden = false;
  428. // /62a88db47fed8b2d94f30000 ==> /path/to/page
  429. if (isPermalink && page.isEmpty) {
  430. props.currentPathname = page.path;
  431. }
  432. // /path/to/page ==> /62a88db47fed8b2d94f30000
  433. if (!isPermalink && !page.isEmpty) {
  434. const isToppage = pagePathUtils.isTopPage(props.currentPathname);
  435. if (!isToppage) {
  436. props.currentPathname = `/${page._id}`;
  437. }
  438. }
  439. if (!props.skipSSR) {
  440. props.yjsData = await crowi.pageService.getYjsData(page._id.toString());
  441. }
  442. }
  443. }
  444. // async function injectPageUserInformation(context: GetServerSidePropsContext, props: Props): Promise<void> {
  445. // const req: CrowiRequest = context.req as CrowiRequest;
  446. // const { crowi } = req;
  447. // const UserModel = crowi.model('User');
  448. // if (isUserPage(props.currentPagePath)) {
  449. // const user = await UserModel.findUserByUsername(UserModel.getUsernameByPath(props.currentPagePath));
  450. // if (user != null) {
  451. // props.pageUser = JSON.stringify(user.toObject());
  452. // }
  453. // }
  454. // }
  455. function injectServerConfigurations(context: GetServerSidePropsContext, props: Props): void {
  456. const req: CrowiRequest = context.req as CrowiRequest;
  457. const { crowi } = req;
  458. const {
  459. configManager, searchService, aclService, fileUploadService,
  460. slackIntegrationService, passportService,
  461. } = crowi;
  462. props.aiEnabled = configManager.getConfig('app:aiEnabled');
  463. props.limitLearnablePageCountPerAssistant = configManager.getConfig('openai:limitLearnablePageCountPerAssistant');
  464. props.isSearchServiceConfigured = searchService.isConfigured;
  465. props.isSearchServiceReachable = searchService.isReachable;
  466. props.isSearchScopeChildrenAsDefault = configManager.getConfig('customize:isSearchScopeChildrenAsDefault');
  467. props.elasticsearchMaxBodyLengthToIndex = configManager.getConfig('app:elasticsearchMaxBodyLengthToIndex');
  468. props.isRomUserAllowedToComment = configManager.getConfig('security:isRomUserAllowedToComment');
  469. props.isSlackConfigured = slackIntegrationService.isSlackConfigured;
  470. // props.isMailerSetup = mailService.isMailerSetup;
  471. props.isAclEnabled = aclService.isAclEnabled();
  472. // props.hasSlackConfig = slackNotificationService.hasSlackConfig();
  473. props.drawioUri = configManager.getConfig('app:drawioUri');
  474. // props.highlightJsStyle = configManager.getConfig('customize:highlightJsStyle');
  475. props.isAllReplyShown = configManager.getConfig('customize:isAllReplyShown');
  476. props.showPageSideAuthors = configManager.getConfig('customize:showPageSideAuthors');
  477. props.isContainerFluid = configManager.getConfig('customize:isContainerFluid');
  478. props.isEnabledStaleNotification = configManager.getConfig('customize:isEnabledStaleNotification');
  479. props.disableLinkSharing = configManager.getConfig('security:disableLinkSharing');
  480. props.isUploadAllFileAllowed = fileUploadService.getFileUploadEnabled();
  481. props.isUploadEnabled = fileUploadService.getIsUploadable();
  482. props.isLocalAccountRegistrationEnabled = passportService.isLocalStrategySetup
  483. && configManager.getConfig('security:registrationMode') !== RegistrationMode.CLOSED;
  484. props.adminPreferredIndentSize = configManager.getConfig('markdown:adminPreferredIndentSize');
  485. props.isIndentSizeForced = configManager.getConfig('markdown:isIndentSizeForced');
  486. props.isEnabledAttachTitleHeader = configManager.getConfig('customize:isEnabledAttachTitleHeader');
  487. props.sidebarConfig = {
  488. isSidebarCollapsedMode: configManager.getConfig('customize:isSidebarCollapsedMode'),
  489. isSidebarClosedAtDockMode: configManager.getConfig('customize:isSidebarClosedAtDockMode'),
  490. };
  491. props.rendererConfig = {
  492. isEnabledLinebreaks: configManager.getConfig('markdown:isEnabledLinebreaks'),
  493. isEnabledLinebreaksInComments: configManager.getConfig('markdown:isEnabledLinebreaksInComments'),
  494. isEnabledMarp: configManager.getConfig('customize:isEnabledMarp'),
  495. adminPreferredIndentSize: configManager.getConfig('markdown:adminPreferredIndentSize'),
  496. isIndentSizeForced: configManager.getConfig('markdown:isIndentSizeForced'),
  497. drawioUri: configManager.getConfig('app:drawioUri'),
  498. plantumlUri: configManager.getConfig('app:plantumlUri'),
  499. // XSS Options
  500. isEnabledXssPrevention: configManager.getConfig('markdown:rehypeSanitize:isEnabledPrevention'),
  501. sanitizeType: configManager.getConfig('markdown:rehypeSanitize:option'),
  502. customTagWhitelist: configManager.getConfig('markdown:rehypeSanitize:tagNames'),
  503. customAttrWhitelist: configManager.getConfig('markdown:rehypeSanitize:attributes') != null
  504. ? JSON.parse(configManager.getConfig('markdown:rehypeSanitize:attributes'))
  505. : undefined,
  506. highlightJsStyleBorder: configManager.getConfig('customize:highlightJsStyleBorder'),
  507. };
  508. props.ssrMaxRevisionBodyLength = configManager.getConfig('app:ssrMaxRevisionBodyLength');
  509. }
  510. /**
  511. * for Server Side Translations
  512. * @param context
  513. * @param props
  514. * @param namespacesRequired
  515. */
  516. async function injectNextI18NextConfigurations(context: GetServerSidePropsContext, props: Props, namespacesRequired?: string[] | undefined): Promise<void> {
  517. const nextI18NextConfig = await getNextI18NextConfig(serverSideTranslations, context, namespacesRequired);
  518. props._nextI18Next = nextI18NextConfig._nextI18Next;
  519. }
  520. const getAction = (props: Props): SupportedActionType => {
  521. if (props.isNotCreatable) {
  522. return SupportedAction.ACTION_PAGE_NOT_CREATABLE;
  523. }
  524. if (props.isForbidden) {
  525. return SupportedAction.ACTION_PAGE_FORBIDDEN;
  526. }
  527. if (props.isNotFound) {
  528. return SupportedAction.ACTION_PAGE_NOT_FOUND;
  529. }
  530. if (pagePathUtils.isUsersHomepage(props.pageWithMeta?.data.path ?? '')) {
  531. return SupportedAction.ACTION_PAGE_USER_HOME_VIEW;
  532. }
  533. return SupportedAction.ACTION_PAGE_VIEW;
  534. };
  535. export const getServerSideProps: GetServerSideProps = async(context: GetServerSidePropsContext) => {
  536. const req = context.req as CrowiRequest;
  537. const { user } = req;
  538. const result = await getServerSideCommonProps(context);
  539. // check for presence
  540. // see: https://github.com/vercel/next.js/issues/19271#issuecomment-730006862
  541. if (!('props' in result)) {
  542. throw new Error('invalid getSSP result');
  543. }
  544. const props: Props = result.props as Props;
  545. if (props.redirectDestination != null) {
  546. return {
  547. redirect: {
  548. permanent: false,
  549. destination: props.redirectDestination,
  550. },
  551. };
  552. }
  553. if (user != null) {
  554. props.currentUser = user.toObject();
  555. }
  556. try {
  557. await injectPageData(context, props);
  558. }
  559. catch (err) {
  560. if (err instanceof MultiplePagesHitsError) {
  561. props.isIdenticalPathPage = true;
  562. }
  563. else {
  564. throw err;
  565. }
  566. }
  567. await injectRoutingInformation(context, props);
  568. injectServerConfigurations(context, props);
  569. await injectNextI18NextConfigurations(context, props, ['translation']);
  570. addActivity(context, getAction(props));
  571. return {
  572. props,
  573. };
  574. };
  575. export default Page;